package com.company.config;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class PerformanceFilter implements Filter {

    private static final ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Filter 初始化时调用
        log.info("Initializing PerformanceFilter");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        // 请求到达时，记录开始时间
        startTimeThreadLocal.set(System.currentTimeMillis());
        
        try {
            // 继续执行请求链
            chain.doFilter(request, response);
        } finally {
            // 请求完成后，计算耗时
            long startTime = startTimeThreadLocal.get();
            long elapsedTime = System.currentTimeMillis() - startTime;
            
            // 清除 ThreadLocal 中的数据，避免内存泄漏
            startTimeThreadLocal.remove();
            
            // 打印耗时或者进行其他的耗时统计逻辑
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            String requestURI = httpServletRequest.getRequestURI();
            log.info("Request to {} took {} ms", requestURI, elapsedTime);
        }
    }

    @Override
    public void destroy() {
        // Filter 销毁时调用
        log.info("PerformanceFilter  destroyed")    ;
    }
}
